package com.example.hybridmobiledemo.module.main.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.example.hybridmobiledemo.R;
import com.example.hybridmobiledemo.databinding.FragmentMainBinding;
import com.example.hybridmobiledemo.module.main.bean.NewTypeInfo;
import com.example.hybridmobiledemo.module.main.bean.SCNewsAllInfo;
import com.example.hybridmobiledemo.module.main.fragment.news.CityBuildFragment;
import com.example.hybridmobiledemo.module.main.fragment.news.EcoFragment;
import com.example.hybridmobiledemo.module.main.fragment.news.EntertainmentFragment;
import com.example.hybridmobiledemo.module.main.fragment.news.InternationalFragment;
import com.example.hybridmobiledemo.module.main.fragment.news.LawFragment;
import com.example.hybridmobiledemo.module.main.fragment.news.ScienceFragment;
import com.example.hybridmobiledemo.module.main.fragment.news.SociologyFragment;
import com.example.hybridmobiledemo.module.main.fragment.news.SportFragment;
import com.example.hybridmobiledemo.module.main.model.hospital.Medical;
import com.example.hybridmobiledemo.module.main.model.shop.classification.ShopActivity;
import com.example.hybridmobiledemo.module.main.model.traffic.BusList;
import com.example.hybridmobiledemo.module.main.model.travel.SmartTourism;
import com.example.hybridmobiledemo.util.OkHttpUtils;
import com.example.hybridmobiledemo.view.MyPagerAdapter;
import com.example.hybridmobiledemo.view.ViewPageAdapter;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MainFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MainFragment extends Fragment implements ViewPager.OnPageChangeListener {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private FragmentMainBinding binding;
    private LinearLayout lineHospital, lineMake, lineTraffic, lineTravel, lineShop;
    private LinearLayout llPoint;
    private ViewPager vp;
    private int lastPosition;
    private ArrayList<String> imgUrls = new ArrayList<>();
    private ArrayList<ImageView> imageViews; //存放图片的集合
    private boolean isRunning = false; //viewpager是否在自动轮询
    private TabLayout tabLayout;
    private ViewPager2 viewPager2;
    List<Fragment> fragmentList = new ArrayList<>();
    private String UserID;

    public MainFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MainFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MainFragment newInstance(String param1, String param2) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentMainBinding.inflate(inflater, container, false);
        SharedPreferences sp = getActivity().getSharedPreferences("UserID", Context.MODE_PRIVATE);
        UserID = sp.getString("UserID", "ODky");
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.builder()
                        .url("interface/SCNews/getAll")
                        .addParam("userId", UserID)
                        .get()
                        .async(new OkHttpUtils.AsyncCallBack() {
                            @Override
                            public void onResponse(String json) {
                                Gson gson = new Gson();
                                SCNewsAllInfo info = gson.fromJson(json, SCNewsAllInfo.class);
                                List<SCNewsAllInfo.DataBean> beans = info.getData();
                                for (int i = 0; i < beans.size(); i++) {
                                    String content = beans.get(i).getContent();
                                    List<String> urls = getImgList(content, "http://", ".jpg\" d");
                                    for (String u : urls) {
                                        String url = u.substring(0, u.length()-3);
                                        imgUrls.add(url);
                                    }
                                }
                                initView();
                                initData();
                                initAdapter();
                                new Thread(() -> {
                                    isRunning = true;
                                    while (isRunning) {
                                        try {
                                            Thread.sleep(3000);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        if (isRunning) {
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    vp.setCurrentItem(vp.getCurrentItem() + 1);
                                                }
                                            });
                                        }
                                    }
                                }).start();
                            }

                            @Override
                            public void onFailure(Exception e) {

                            }
                        });
            }
        }).start();
        return binding.getRoot();
    }

    private void initAdapter() {
        llPoint.getChildAt(0).setBackgroundResource(R.drawable.radiobutton_on_background);
        lastPosition = 0;
        MyPagerAdapter adapter = new MyPagerAdapter();
        adapter.setImageViews(imageViews);
        vp.setAdapter(adapter);
        vp.setCurrentItem(5000000);
    }

    private void initData() {
        imageViews = new ArrayList<>();
        ImageView imageView;
        View pointView;
        for (int i = 0; i < 5; i++) {
            imageView = new ImageView(getContext());
            int rollImg = (int) (Math.random() * imgUrls.size());
            try {
                Glide.with(getContext()).load(imgUrls.get(rollImg)).into(imageView);
            } catch (Exception e) {
                Glide.with(getContext()).load(R.drawable.ic_launcher_background).into(imageView);
            }
            imageViews.add(imageView);
            pointView = new View(getContext());
            pointView.setBackgroundResource(R.drawable.radiobutton_off_background);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(25, 25);
            if (i != 0) {
                layoutParams.leftMargin = 10;
            }
            llPoint.addView(pointView, layoutParams);
        }
    }

    private Drawable urlToDrawable(String url)
    {
        try
        {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        }catch (Exception e) {
            System.out.println("Exc="+e);
            return null;
        }
    }
    public static List<String> getImgList(String info,String begin,String end){
        //通过起始字符拆分成数组
        String[] split = info.split(begin);
        List<String> list = new ArrayList<>();
        //遍历，从第二个元素开始取值（第一个元素为无效元素）
        for (int i = 1; i < split.length; i++) {
            String str = split[i].substring(0,split[i].lastIndexOf(end)+end.length());
            if (str.length() > end.length()) {
                list.add(begin+str);
            }
        }
        return list;
    }

    private void initView() {
        llPoint = (LinearLayout) binding.llPoint;
        lineHospital = binding.lineHospital;
        lineMake = binding.lineMake;
        lineTraffic = binding.lineTraffic;
        lineTravel = binding.lineTravel;
        lineShop = binding.lineShop;
        vp = (ViewPager) binding.vp;
        vp.setOnPageChangeListener(this);
        tabLayout = binding.tabLayout;
        viewPager2 = binding.viewPager2;
        lineHospital.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), Medical.class));
            }
        });
        lineMake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
        lineTraffic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), BusList.class));
            }
        });
        lineTravel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), SmartTourism.class));
            }
        });
        lineShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), ShopActivity.class));
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.builder()
                        .url("interface/SCNewsType/getAll")
                        .addParam("userId", UserID)
                        .get()
                        .async(new OkHttpUtils.AsyncCallBack() {
                            @Override
                            public void onResponse(String json) {
                                Gson gson = new Gson();
                                NewTypeInfo info = gson.fromJson(json, NewTypeInfo.class);
                                List<NewTypeInfo.DataBean> list = info.getData();
                                for (int i = 0; i < list.size(); i++) {
                                    String name = list.get(i).getName();
                                    String type = name.substring(0, name.length()-2);
                                    String id = String.valueOf(list.get(i).getId());
                                    switch (type) {
                                        case "科教":
                                            fragmentList.add(ScienceFragment.newInstance("科教",
                                                    "", id));
                                            break;
                                        case "城建":
                                            fragmentList.add(CityBuildFragment.newInstance("城建",
                                                    "", id));
                                            break;
                                        case "经济":
                                            fragmentList.add(EcoFragment.newInstance("经济",
                                                    "", id));
                                            break;
                                        case "政法":
                                            fragmentList.add(LawFragment.newInstance("政法",
                                                    "", id));
                                            break;
                                        case "社会":
                                            fragmentList.add(SociologyFragment.newInstance("社会",
                                                    "", id));
                                            break;
                                        case "娱乐":
                                            fragmentList.add(EntertainmentFragment.newInstance("娱乐",
                                                    "", id));
                                            break;
                                        case "体育":
                                            fragmentList.add(SportFragment.newInstance("体育",
                                                    "", id));
                                            break;
                                        case "国际":
                                            fragmentList.add(InternationalFragment.newInstance("国际",
                                                    "", id));
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                ViewPageAdapter adapter = new ViewPageAdapter(getActivity().getSupportFragmentManager(),
                                        getActivity().getLifecycle(), fragmentList);
                                viewPager2.setAdapter(adapter);
                                new TabLayoutMediator(tabLayout, viewPager2, true, new TabLayoutMediator.TabConfigurationStrategy() {
                                    @Override
                                    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                                        tab.setText(fragmentList.get(position).getArguments().getString("title"));
                                    }
                                }).attach();
                            }

                            @Override
                            public void onFailure(Exception e) {
                            }
                        });
            }
        }).start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        int newPosition = position % 5;
        llPoint.getChildAt(lastPosition).setBackgroundResource(R.drawable.radiobutton_off_background);
        llPoint.getChildAt(newPosition).setBackgroundResource(R.drawable.radiobutton_on_background);
        lastPosition = newPosition;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
}